package com.thd.springboottest.nginxproxy;

import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.IOException;

/**
 * com.thd.springboottest.nginxproxy.PathFilter
 *
 * @author: wanglei62
 * @DATE: 2022/10/24 17:59
 **/
@Component
@WebFilter(filterName = "MyFilter",
        /**
         * 通配符（*）表示对所有的web资源进行拦截
        */
        urlPatterns = "/*"
)
public class PathFilter implements Filter {
    /**
     * 用于查看nginx发送请求的路径
     * explain:过滤的具体操作
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        System.out.println("请求地址:"+request.getRequestURI());

        filterChain.doFilter(servletRequest,servletResponse);

        /*
        HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper((HttpServletResponse) servletResponse);

        // 请求url中包含/hello||/online,继续执行
        if (request.getRequestURI().contains("/hello")
                || request.getRequestURI().contains("/online") ){
            // 交给下一个过滤器或servlet处理
            filterChain.doFilter(servletRequest,servletResponse);
        }else {
            // 请求url不包含/hello||/online,重定向到/online接口
            wrapper.sendRedirect("/entry/online");
        }*/
    }

}
